package com.ibl.rover.lite.client.Sync.Parser;

import java.io.ByteArrayInputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import com.mobile.sync.client.Sync.ResponseInfo;

public class ResponseInfoParser {
	private SyncResponseData responseData = null;

	public ResponseInfoParser() {
	}

	
	public void parse(byte[] array) {
		try {
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();
			responseData = new SyncResponseData();
			xr.setContentHandler(responseData);
			ByteArrayInputStream stream = new ByteArrayInputStream(array);
			xr.parse(new InputSource(stream));
			stream.close();
		} catch (RuntimeException ex) {

		} catch (Exception ex) {

		}

	}

	public ResponseInfo getResponseInfo() {
		return responseData.getResponseInfo();
	}

	public static class SyncResponseData extends DefaultHandler {
		private static final String RESPONSE_MESSAGE = "responseMessage";
		private static final String RESPONSE_CODE = "responseCode";
		private static final String HEAD = "HEAD";
		private static final String VALUE = "value";
		private ResponseInfo response = null;

		@Override
		public void startDocument() throws SAXException {
			super.startDocument();
		}

		@Override
		public void endDocument() throws SAXException {
			super.endDocument();
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			if (localName.equalsIgnoreCase(HEAD)) {
				response = new ResponseInfo();
			} else if (localName.equalsIgnoreCase(RESPONSE_MESSAGE)) {
				response.setServerMessage(attributes.getValue(VALUE));
			} else if (localName.equalsIgnoreCase(RESPONSE_CODE)) {
				response.setServerCode(attributes.getValue(VALUE));
			}
		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			if (localName.equalsIgnoreCase(HEAD)) {
				throw new RuntimeException("[Parsing Done]");
			}
		}

		public ResponseInfo getResponseInfo() {
			return response;
		}

	}

}
